package com.chuangshu.chuangshuteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chuangshu.chuangshuteam.config.BaseContext;
import com.chuangshu.chuangshuteam.dto.FileMetadataDto;
import com.chuangshu.chuangshuteam.dto.RecruitmentCyclesDTO;
import com.chuangshu.chuangshuteam.dto.Result;
import com.chuangshu.chuangshuteam.entity.BusinessKey;
import com.chuangshu.chuangshuteam.entity.FileInfo;
import com.chuangshu.chuangshuteam.entity.RecruitmentCycles;
import com.chuangshu.chuangshuteam.mapper.FileInfoMapper;
import com.chuangshu.chuangshuteam.mapper.RecruitmentCyclesMapper;
import com.chuangshu.chuangshuteam.service.RecruitmentCyclesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangshu.chuangshuteam.vo.RecruitmentCyclesVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author k
 * @since 2025-09-21
 */
@Slf4j
@Service
public class RecruitmentCyclesServiceImpl extends ServiceImpl<RecruitmentCyclesMapper, RecruitmentCycles> implements RecruitmentCyclesService {

    @Autowired
     RecruitmentCyclesMapper recruitmentCyclesMapper;
    @Autowired
    FileInfoMapper fileInfoMapper;

        /**
     * 添加招聘信息周期信息
     *
     * @param recruitmentCyclesVO 招聘周期信息传输对象，包含招聘周期的基本信息和附件信息
     */
    @Override
    public void addInfo(RecruitmentCyclesVO recruitmentCyclesVO) {
        List<FileMetadataDto> attachments = recruitmentCyclesVO.getAttachments();
        // 如果没有附件信息，直接添加招聘周期信息
        if (attachments==null||attachments.isEmpty()){
            addRecruitmentCycles(recruitmentCyclesVO);
        }else {
            // 如果有附件信息，先添加招聘周期基本信息，再处理附件
            RecruitmentCycles recruitmentCycles = addRecruitmentCycles(recruitmentCyclesVO);
            Long id = recruitmentCycles.getId();
            // 遍历附件列表，将每个附件信息保存到文件信息表中
            for (int i = 0; i < attachments.size(); i++) {
                FileInfo fileInfo = new FileInfo();
                BeanUtils.copyProperties(attachments.get(i),fileInfo);
                fileInfo.setBusinessId(id);
                fileInfo.setBusinessType(BusinessKey.RECRUITMENT_CYCLES_ID);
                fileInfoMapper.insert(fileInfo);
            }

        }
    }

    @Override
    public Result getByPage(Integer page, Integer pageSize) {
        // 创建分页对象
        Page<RecruitmentCycles> pageParam = new Page<>(page, pageSize);

        QueryWrapper<RecruitmentCycles> queryWrapper = new QueryWrapper<>();
        // 例如，只查询状态为 "PUBLISHED" 的
        queryWrapper.eq("status", "open");
        // 按创建时间降序排序
        queryWrapper.orderByDesc("created_at");
        // 执行分页查询
        Page<RecruitmentCycles> resultPage = this.page(pageParam,queryWrapper);

        // 创建 VO 分页对象
        Page<RecruitmentCyclesDTO> voPage = new Page<>(page, pageSize);
        voPage.setTotal(resultPage.getTotal());
        voPage.setPages(resultPage.getPages());

        // 转换实体对象为 VO 对象
        List<RecruitmentCyclesDTO> DTOList = new ArrayList<>();
        for (RecruitmentCycles recruitmentCycles : resultPage.getRecords()) {
            RecruitmentCyclesDTO DTO = new RecruitmentCyclesDTO();
            BeanUtils.copyProperties(recruitmentCycles, DTO);
            DTOList.add(DTO);
        }
        voPage.setRecords(DTOList);

        return Result.ok(voPage);

}

    @Override
    public RecruitmentCyclesDTO queryById(Long id) {
        RecruitmentCyclesDTO recruitmentCyclesDTO = recruitmentCyclesMapper.getById(id, BusinessKey.RECRUITMENT_CYCLES_ID);
        return recruitmentCyclesDTO;
    }

    @Override
    public void updateInfo(RecruitmentCyclesVO recruitmentCyclesVO) {
        // 获取要更新的招聘周期信息
        RecruitmentCycles recruitmentCycles = new RecruitmentCycles();
        ObjectMapper objectMapper = new ObjectMapper();

        recruitmentCycles.setId(recruitmentCyclesVO.getId());
        recruitmentCycles.setTitle(recruitmentCyclesVO.getTitle());
        recruitmentCycles.setDescription(recruitmentCyclesVO.getDescription());
        recruitmentCycles.setStartDate(recruitmentCyclesVO.getStartDate());
        recruitmentCycles.setEndDate(recruitmentCyclesVO.getEndDate());

        List<String> directions = recruitmentCyclesVO.getDirections();
        try {
            // 将方向列表转换为JSON字符串并保存
            if (directions != null && !directions.isEmpty()) {
                recruitmentCycles.setDirections(objectMapper.writeValueAsString(directions));
            }
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }

        // 更新招聘周期信息
        this.updateById(recruitmentCycles);
    }
    /**
     * 添加招聘周期
     *
     * @param recruitmentCyclesVO 招聘周期值对象，包含招聘周期的相关信息
     * @return 添加成功的招聘周期实体对象
     */
    private RecruitmentCycles addRecruitmentCycles(RecruitmentCyclesVO recruitmentCyclesVO) {
        RecruitmentCycles recruitmentCycles = new RecruitmentCycles();
        ObjectMapper objectMapper = new ObjectMapper();
        recruitmentCycles.setDescription(recruitmentCyclesVO.getDescription());
        List<String> directions = recruitmentCyclesVO.getDirections();
        try {
            // 将方向列表转换为JSON字符串并保存
            if (directions!=null&&!directions.isEmpty()) {
                recruitmentCycles.setDirections(objectMapper.writeValueAsString( directions));
            }
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        recruitmentCycles.setTeamId(1L);
        recruitmentCycles.setTitle(recruitmentCyclesVO.getTitle());
        recruitmentCycles.setStartDate(recruitmentCyclesVO.getStartDate());
        recruitmentCycles.setEndDate(recruitmentCyclesVO.getEndDate());
        recruitmentCycles.setCreatedBy(BaseContext.getCurrentId());
        recruitmentCycles.setStatus("open");
        recruitmentCyclesMapper.insert(recruitmentCycles);
        System.out.println("回显id"+recruitmentCycles.getId());
        return recruitmentCycles;
    }

    @Override
public void deleteById(Long id) {
    // 先删除附件信息
    QueryWrapper<FileInfo> fileQueryWrapper = new QueryWrapper<>();
    fileQueryWrapper.eq("business_id", id)
                    .eq("business_type", BusinessKey.RECRUITMENT_CYCLES_ID);
    fileInfoMapper.delete(fileQueryWrapper);

    // 再删除招聘周期信息
        recruitmentCyclesMapper.deleteById(id);
}


}
